<script>

export default {
  name: "MyAccount",
  data() {
    return {
      loading: false,
      activeNames: ['1'],
      isEditing: false,
      showCropper: false,
      defaultAvatar: require('../../assets/defaultavatar.png'), // 本地默认头像
      originalData: {}, // 用于保存原始数据
      prevAvatarUrl: null,
      notifications: [],
      form: {
        id:'',
        no:'',
        name:'',
        password:undefined,
        age:'',
        sex:2,
        phoneNum:'',
        roleId: '',
        email:'',
        address:'',
        avatar:'',
        avatarBytes: '',
        avatarFile: null
      }
    }
  },
  methods: {
    handleChange(val) {
      console.log(val);
    },
    // 触发文件选择
    triggerFileInput() {
      if (this.isEditing) {
        this.$refs.fileInput.click()
      }
    },
    handleImageError(e) {
      e.target.src = this.defaultAvatar; // 加载失败时使用默认头像
    },
    handleFileUpload(e) {
      const file = e.target.files[0];
      if (!file) return
      // 验证文件类型
      if (!['image/png', 'image/jpeg'].includes(file.type)) {
        this.$notify.error({ title: '错误', message: '请选择图片文件' });
        return
      }
      if (file.size > 2 * 1024 * 1024) {
        this.$notify.error({
          title: '错误',
          message: '图片大小不能超过2MB'
        });
        return
      }
      //直接存储文件对象
      this.form.avatarFile = file;
      const reader = new FileReader();
      reader.onload = (e) => {
        this.form.avatar = e.target.result
        this.showCropper = true
      }
      reader.readAsDataURL(file)
    },

    async doMod(){//更新
      try {
        if (this.form.avatarFile) {
          const formData = new FormData();
          formData.append('file',this.form.avatarFile);
          formData.append('userId',this.form.id)

          const uploadRes = await this.$axios.post(
              this.$httpUrl + '/user/uploadAvatar',
              formData,
              {
                headers: {
                  'Content-Type':'multipart/form-data'
                }
              }
          );

          if (uploadRes.data.code !== 200) {
            throw  new  Error('头像上传失败');
          }
          //清除临时文件引用
          this.form.avatarFile = null;
        }
        const submitData = {
          id: this.form.id,
          no: this.form.no,
          name: this.form.name,
          password: this.form.password || undefined,
          age: this.form.age,
          sex: this.form.sex,
          phoneNum: this.form.phoneNum,
          email: this.form.email,
          address: this.form.address
        };
        const res = await this.$axios.post(
            this.$httpUrl + '/user/update',
            submitData
        ).then(res=>res.data)
            .then(res=>{
          console.log(res)
          if (res.code === 200){
            this.$message({
              showClose: true,
              message: '操作成功！',
              type: 'success'
            });
            this.$store.commit('updateUser',submitData)
            this.fetchUserData()
          }else{
            this.$message({
              showClose: true,
              message: '操作失败！',
              type: 'error'
            });
          }
        });
      } catch (error) {
        console.error('保存失败：',error);
        this.$message.error('操作失败：' + error.message);
      }
    },
    save(){//保存提交数据至后端(更新或新增)
      this.$refs.form.validate((valid) => {
        if (valid) {
            this.doMod();
        } else {
          console.log('error submit!')
          return false;
        }
      });
    },
      startEditing() {
      this.originalData = { ...this.form } // 保存原始数据副本
      this.isEditing = true
    },
    cancelEditing() {
      this.form = { ...this.originalData } // 恢复原始数据
      this.isEditing = false
    },
    Finish() {
      this.$router.replace("/")
    },
    async fetchUserData() {
      this.loading = true;
      try {
        const res = await this.$axios.post(this.$httpUrl+'/user/listPageC1', {
          pageSize: 1,
          pageNum: 1,
          param:{name: this.user.name}
        });
        console.log('调试信息-响应数据:', res);
        if (res.data.code === 200 && res.data.data?.length > 0) {
          const userData = res.data.data[0];
          console.log('原始用户数据：',userData);
          const baseData = {
            id: userData.id,
            no: userData.no,
            name: userData.name || '未填写',
            password: userData.password,
            phoneNum: userData.phoneNum || '未填写',
            email: userData.email || '未填写',
            address: userData.address || '未填写',
            sex: Number(userData.sex) === 1 ? 1 : 2, // 强制转换为数字
            age: userData.age ? userData.age.toString() : '',
            roleId: userData.roleId,
            avatar: this.defaultAvatar // 默认值
          };
          console.log('处理后数据：', baseData);
          if (userData.id) {
            try {
              const avatarUrl = `${this.$httpUrl}/user/avatar/${userData.id}?t=${Date.now()}`;
              const avatarRes = await this.$axios.get(avatarUrl,
                  {responseType:'blob'}
              );

              if (avatarRes.data.size > 0) {
                const blob = new Blob([avatarRes.data], {
                  type: avatarRes.headers['content-type'] || 'image/jpeg'
                });

                const url = URL.createObjectURL(blob);
                baseData.avatar = url;

                this.$nextTick(() => {
                  if (this.prevAvatarUrl) {
                    URL.revokeObjectURL(this.prevAvatarUrl);
                  }
                  this.prevAvatarUrl = url;  // 存储当前URL用于后续清理
                });
              }
            } catch (error) {
              console.error('头像加载失败：',error);
            }
          }

          Object.keys(baseData).forEach(key => {
            this.$set(this.form, key, baseData[key]);
          });
        }
      } catch (error) {
        console.error('请求失败:', error);
        this.$message.error('数据加载失败');
        this.form = this.getDefaultFormData();
      } finally {
        this.loading = false;
      }
    },
    getDefaultFormData() {
      return {
        id: '',
        no: '',
        name: '加载中...',
        password: undefined,
        age: '',
        sex: 2,
        phoneNum: '未填写',
        roleId: '',
        email: '未填写',
        address: '未填写',
        avatar: this.defaultAvatar
      };
    },
    async loadNotifications() {
      const userId = this.$store.state.user.no; // 当前用户账号
      const res = await this.$axios.get(`/notification/userList?userId=${userId}`);
      if (res.data.code === 200) {
        this.notifications = res.data.data;
      }
    },
    formatTime(time) {
      return new Date(time).toLocaleString('zh-CN');
    },
  },
  computed: {
    user() {
      return this.$store.state.user || {};
    },
    unreadCount() {
      return this.notifications.filter(n => n.status === 0).length;
    }
  },
  watch: {
    immediate: true,
    user(newVal) {
      if (newVal) this.fetchUserData();
    }
  },
  mounted() {
    console.log('当前用户信息：', this.user);
    if (!this.user) {
      this.$message.error('请先登录');
      this.$router.push('/LoginPage');
    } else {
      this.fetchUserData();
    }
    this.loadNotifications();
  },
  beforeDestroy() {
    if (this.form.avatar && this.form.avatar.startsWith('blob:')) {
      URL.revokeObjectURL(this.form.avatar);
    }
    //清理临时文件引用
    this.form.avatarFile = null;
  }

}
</script>

<template>
  <div style="background: #fff8e1; min-height: 100vh">
    <div class="header" >
      <el-link :underline="false"
               class="back-link"
               @click.native="Finish"
               icon="el-icon-back"
      >
        返回
      </el-link>
      <h1 class="title">
        My Account
        <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="notification-badge">
          <i class="el-icon-bell"></i>
        </el-badge>
      </h1>
      <div class="divider"></div>
    </div>
    <el-collapse v-model="activeNames" @change="handleChange" class="custom-collapse">
      <el-collapse-item style="margin-left: 15px" title="个人信息" name="1" class="custom-collapse-item">
        <template v-if="loading">
          <div class="loading-container">
            <i class="el-icon-loading"></i>
            正在加载用户数据...
          </div>
        </template>
        <template v-else>
          <div class="account-container">
            <div class="avatar-section">
              <div
                  class="avatar-wrapper"
                  @click="triggerFileInput"
                  :class="{ 'editable': isEditing }"
              >
                <img
                    :src="form.avatar || defaultAvatar"
                    class="avatar"
                    alt="用户头像"
                    @error="handleImageError"
                >
                <div class="avatar-mask" v-if="isEditing">
                  <i class="el-icon-camera"></i>
                </div>
              </div>
              <input
                  type="file"
                  ref="fileInput"
                  accept="image/*"
                  @change="handleFileUpload"
                  style="display: none;"
              >
            </div>
            <!-- 信息表单 -->
            <div class="form-container">
              <el-form ref="form" :model="form" label-position="left" class="custom-form">
                <!-- 第一列 -->
                <div class="form-column">
                  <el-form-item prop="no" class="custom-form-item">
                    <template slot="label">
                      <i class="el-icon-user"></i>
                      <span>账号：</span>
                    </template>
                    <el-input
                        v-model="form.no"
                        readonly
                        class="read-only"
                        :placeholder="form.no === '未填写' ? '暂无信息' : '系统自动生成'"
                    >
                      <template #suffix>
                        <i class="el-icon-view" style="color: #909399"></i>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="name" class="custom-form-item">
                    <template slot="label">
                      <i class="el-icon-user-solid"></i>
                      <span>姓名：</span>
                    </template>
                    <el-input
                        v-model="form.name"
                        :readonly="!isEditing"
                        :placeholder="form.name === '未填写' ? '暂无信息' : '请输入姓名'"
                    ></el-input>
                  </el-form-item>
                  <el-form-item prop="age" class="custom-form-item">
                    <template slot="label">
                      <i class="el-icon-date"></i>
                      <span>年龄：</span>
                    </template>
                    <el-input
                        v-model="form.age"
                        :readonly="!isEditing"
                        :placeholder="form.age === '未填写' ? '暂无信息' : '请输入年龄'"
                        type="number"
                    ></el-input>
                  </el-form-item>
                  <el-form-item prop="sex" class="custom-form-item">
                    <template slot="label">
                      <i class="el-icon-magic-stick"></i>
                      <span>性别：</span>
                    </template>
                    <el-radio-group
                        v-model="form.sex"
                        :disabled="!isEditing"
                    >
                      <el-radio :label="1">男</el-radio>
                      <el-radio :label="2">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>

                <!-- 第二列 -->
                <div class="form-column">
                  <el-form-item label="密码：" prop="password" class="custom-form-item">
                    <template slot="label">
                      <i class="el-icon-lock"></i>
                      <span>密码：</span>
                    </template>
                    <el-input v-if="isEditing"
                              v-model="form.password"
                              :placeholder="form.password === '未填写' ? '暂无信息' : '修改密码'"
                              show-password
                    ></el-input>
                    <el-input
                        v-else
                        readonly
                        class="read-only"
                    >
                      <template #prefix>
                        <i class="el-icon-lock" style="color: #909399"></i>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="联系电话：" prop="phoneNum" class="custom-form-item">
                    <template slot="label">
                      <i class="el-icon-phone"></i>
                      <span>联系电话：</span>
                    </template>
                    <el-input
                        v-model="form.phoneNum"
                        :readonly="!isEditing"
                        :placeholder="form.phoneNum === '未填写' ? '暂无信息' : '请输入联系电话'"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="电子邮件：" prop="email" class="custom-form-item">
                    <template slot="label">
                      <i class="el-icon-message"></i>
                      <span>电子邮件：</span>
                    </template>
                    <el-input
                        v-model="form.email"
                        :readonly="!isEditing"
                        :placeholder="form.email === '未填写' ? '暂无信息' : '请输入电子邮件'"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="联系地址：" prop="address" class="custom-form-item">
                    <template slot="label">
                      <i class="el-icon-location"></i>
                      <span>联系地址：</span>
                    </template>
                    <el-input
                        v-model="form.address"
                        :readonly="!isEditing"
                        :placeholder="form.address === '未填写' ? '暂无信息' : '请输入联系地址'"
                        type="textarea"
                        :rows="2"
                    ></el-input>
                  </el-form-item>
                  <!-- 操作按钮 -->
                  <div class="action-buttons">
                    <button
                        v-if="!isEditing"
                        @click="startEditing"
                        class="edit-btn"
                    >
                      编辑信息
                    </button>
                    <div v-else class="save-group">
                      <button @click="save" class="save-btn">保存</button>
                      <button @click="cancelEditing" class="cancel-btn">取消</button>
                    </div>
                  </div>
                </div>
              </el-form>
            </div>
          </div>
        </template>
      </el-collapse-item>
      <el-collapse-item style="margin-left: 15px" :title="`我的通知 (${unreadCount})`" name="2" class="custom-collapse-item">
        <div>
          <div class="notification-list">
            <el-card v-for="note in notifications" :key="note.id">
              <div class="content">{{ note.content }}</div>
              <div class="status">
                {{ note.status === 1 ? '✅ 已处理' : '❌ 未处理' }}
              </div>
              <div class="time">{{ formatTime(note.createTime) }}</div>
            </el-card>
          </div>
        </div>
      </el-collapse-item>
<!--      <el-collapse-item style="margin-left: 15px" title="效率 Efficiency" name="3" class="custom-collapse-item">
      </el-collapse-item>
      <el-collapse-item style="margin-left: 15px" title="可控 Controllability" name="4" class="custom-collapse-item">
      </el-collapse-item>-->
    </el-collapse>
  </div>
</template>

<style scoped>
.header {
  display: flex;
  gap: 15px;
}
.account-container {
  max-width: 1200px;
  width: 90%;
  margin: 20px auto;
  padding: 30px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.08);
  position: relative;
}
.custom-collapse {
  background: transparent !important;
  border: none;
}
.custom-collapse-item {
  margin: 15px;
  border-radius: 8px !important;
  overflow: hidden;
}

.custom-collapse-item >>> .el-collapse-item__wrap {
  background: #fff8e1 !important;
  border: none;
}
.custom-collapse-item >>> .el-collapse-item__content {
  padding: 0 !important;
  background: #fff8e1;
}
.form-container {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 25px; /* 列间距 */
  padding: 20px;
}
@media (max-width: 992px) {
  .form-container {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  .account-container {
    padding: 20px;
  }

  .custom-form-item {
    margin-bottom: 15px;
  }
}

.custom-form-item {
  display: flex;
  align-items: center;
  margin-bottom: 25px;
}

.custom-form-item >>> .el-form-item__label {
  width: 140px;
  font-size: 15px;
  color: #606266;
  margin-right: 20px;
}
.custom-form-item >>> .el-form-item__label i {
  font-size: 18px;
  margin-right: 8px;
  color: #409EFF;
}
.read-only >>> .el-input__inner {
  background: transparent;
  border: none;
  padding-left: 0;
  cursor: default;
  color: #606266 !important;
}
.read-only >>> .el-input__inner:hover {
  background: transparent !important;
}
.el-input--prefix >>> .el-input__prefix {
  left: 10px;
  display: flex;
  align-items: center;
}
.form-column {
  padding: 0 20px;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.header {
  height: 60px;
  position: relative;
  display: flex;
  align-items: center;
  border-bottom: 1.5px solid #eee;
}
.back-link {
  position: absolute;
  left: 10px;
  z-index: 1;
  /deep/ .el-icon-back {
    margin-right: 5px;
  }
}

.title {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  font-size: 24px;
  color: #66BB6A;
  white-space: nowrap;
  margin-top: 20px;
  margin-bottom: 20px;
}
@media (max-width: 768px) {
  .title {
    font-size: 18px;
  }
  .back-link {
    left: 10px;
  }
}

.divider {
  border-bottom: 1px solid #BDBDBD;
  margin-bottom: 30px;
}
input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

input:focus {
  border-color: #409EFF;
  outline: none;
  box-shadow: 0 0 4px rgba(64, 158, 255, 0.3);
}

.action-buttons {
  margin-top: 40px;
  text-align: right;
}

button {
  padding: 12px 30px;
  font-size: 15px;
  border: none;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  cursor: pointer;
  transition: all 0.3s;
}

.edit-btn {
  background: linear-gradient(135deg, #409EFF, #337ecc);
  color: white;
}

.edit-btn:hover {
  background: #337ecc;
}

.save-group {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.save-btn {
  background: linear-gradient(135deg, #67C23A, #529b2e);
  color: white;
}

.cancel-btn {
  background: #909399;
  color: white;
}

@media (max-width: 768px) {
  .form-item {
    flex-direction: column;
    align-items: flex-start;
  }

  label {
    margin-bottom: 8px;
  }

  input {
    width: 100%;
  }
}
.avatar-section {
  text-align: center;
  margin-bottom: 40px; /* 增大下边距 */
}

.avatar-wrapper {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  position: relative;
  margin: 0 auto;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.3s;
  border: 3px solid rgba(141, 110, 99, 0.62);
  background: rgba(129, 199, 132, 0.16);
}

.avatar-wrapper.editable:hover {
  border-color: #409EFF;
}
.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}
.avatar-wrapper:hover .avatar-mask {
  opacity: 1;
}

.avatar-mask i {
  color: white;
  font-size: 24px;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}

.custom-form {
  display: contents;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.read-only >>> .el-input__inner {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #909399;
  cursor: not-allowed;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .custom-form-item {
    flex-direction: column;
    align-items: flex-start;
  }

}
.notification-list {
  padding: 20px;
}
.el-card {
  margin-bottom: 10px;
}
.status {
  color: #666;
  font-size: 0.9rem;
}
.time {
  color: #999;
  font-size: 0.8rem;
}
.title .notification-badge {
  margin-left: 10px;
  vertical-align: middle;
}
.title .el-badge__content {
  top: 10px;
  right: -5px;
}
</style>